package org.example.wumeng.service.impl;

import org.example.wumeng.mapper.T_userMapper;
import org.example.wumeng.service.T_userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.example.wumeng.pojo.User;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class T_userServiceImpl implements T_userService {

    @Autowired
    private T_userMapper userMapper;

    @Override
    public User login(String username, String password) {
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            throw new IllegalArgumentException("用户名和密码不能为空");
        }

        try {
            User user = userMapper.selectByUsername(username);
            if (user == null || !password.equals(user.getPassword())) {
                throw new RuntimeException("用户名或密码错误");
            }

            if (user.getStatus() != 1) {
                throw new RuntimeException("账户已被禁用");
            }

            // 更新最后登录时间
            user.setLastLoginTime(LocalDateTime.now());
            userMapper.updateLastLoginTime(user.getId(), user.getLastLoginTime());

            return user;
        } catch (Exception e) {
            throw new RuntimeException("登录失败: " + e.getMessage());
        }
    }

    @Override
    public Long register(User user) {
        if (user == null) {
            throw new IllegalArgumentException("用户信息不能为空");
        }
        if (!StringUtils.hasText(user.getUsername())) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (!StringUtils.hasText(user.getPassword())) {
            throw new IllegalArgumentException("密码不能为空");
        }
        if (!StringUtils.hasText(user.getName())) {
            throw new IllegalArgumentException("真实姓名不能为空");
        }

        // 检查用户名是否已存在
        if (userMapper.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        try {
            // 设置默认值（只能注册普通用户）
            user.setUserType("USER");
            user.setRole("user");
            user.setStatus(1);
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());

            int result = userMapper.insert(user);
            if (result <= 0) {
                throw new RuntimeException("注册失败");
            }

            return user.getId();
        } catch (Exception e) {
            throw new RuntimeException("注册失败: " + e.getMessage());
        }
    }

    @Override
    public boolean existsByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            return false;
        }
        return userMapper.existsByUsername(username);
    }

    @Override
    public User getById(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("用户ID不能为空或无效");
        }

        try {
            User user = userMapper.selectById(id);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            return user;
        } catch (Exception e) {
            throw new RuntimeException("查询用户信息失败: " + e.getMessage());
        }
    }

    @Override
    public User getUserInfo(String token) {
        if (!StringUtils.hasText(token)) {
            throw new IllegalArgumentException("Token不能为空");
        }

        try {
            // 简化版token解析，实际应该使用JWT
            if (!token.startsWith("token_")) {
                throw new RuntimeException("无效的token格式");
            }

            String[] parts = token.substring(6).split("_");
            if (parts.length < 2) {
                throw new RuntimeException("无效的token格式");
            }

            Long userId = Long.parseLong(parts[0]);
            User user = getById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            return user;
        } catch (Exception e) {
            throw new RuntimeException("获取用户信息失败: " + e.getMessage());
        }
    }

    @Override
    public void update(User user) {
        if (user == null || user.getId() == null) {
            throw new IllegalArgumentException("用户信息或ID不能为空");
        }

        try {
            user.setUpdateTime(LocalDateTime.now());
            int result = userMapper.updateById(user);
            if (result <= 0) {
                throw new RuntimeException("更新用户信息失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("更新用户信息失败: " + e.getMessage());
        }
    }

    @Override
    public User updateProfile(Long userId, User user) {
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不能为空或无效");
        }
        if (user == null) {
            throw new IllegalArgumentException("用户信息不能为空");
        }

        try {
            // 获取当前用户信息
            User currentUser = getById(userId);
            if (currentUser == null) {
                throw new RuntimeException("用户不存在");
            }

            // 只更新允许修改的字段
            if (StringUtils.hasText(user.getName())) {
                currentUser.setName(user.getName());
            }
            if (StringUtils.hasText(user.getEmail())) {
                currentUser.setEmail(user.getEmail());
            }
            if (StringUtils.hasText(user.getPhone())) {
                currentUser.setPhone(user.getPhone());
            }

            currentUser.setUpdateTime(LocalDateTime.now());
            int result = userMapper.updateById(currentUser);
            if (result <= 0) {
                throw new RuntimeException("更新用户资料失败");
            }

            return currentUser;
        } catch (Exception e) {
            throw new RuntimeException("更新用户资料失败: " + e.getMessage());
        }
    }

    @Override
    public boolean changePassword(Long userId, String currentPassword, String newPassword) {
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不能为空或无效");
        }
        if (!StringUtils.hasText(currentPassword) || !StringUtils.hasText(newPassword)) {
            throw new IllegalArgumentException("密码不能为空");
        }

        try {
            // 获取当前用户信息
            User currentUser = getById(userId);
            if (currentUser == null) {
                throw new RuntimeException("用户不存在");
            }

            // 验证当前密码
            if (!currentPassword.equals(currentUser.getPassword())) {
                throw new RuntimeException("当前密码错误");
            }

            // 更新密码
            currentUser.setPassword(newPassword);
            currentUser.setUpdateTime(LocalDateTime.now());
            int result = userMapper.updateById(currentUser);
            if (result <= 0) {
                throw new RuntimeException("修改密码失败");
            }

            return true;
        } catch (Exception e) {
            throw new RuntimeException("修改密码失败: " + e.getMessage());
        }
    }
//
//    @Override
//    public boolean uploadAvatar(Long userId, String avatarUrl) {
//        if (userId == null || userId <= 0) {
//            throw new IllegalArgumentException("用户ID不能为空或无效");
//        }
//        if (!StringUtils.hasText(avatarUrl)) {
//            throw new IllegalArgumentException("头像URL不能为空");
//        }
//
//        try {
//            // 获取当前用户信息
//            User currentUser = getById(userId);
//            if (currentUser == null) {
//                throw new RuntimeException("用户不存在");
//            }
//
//            // 这里可以添加头像URL字段，暂时返回true
//            // currentUser.setAvatarUrl(avatarUrl);
//            // currentUser.setUpdateTime(LocalDateTime.now());
//            // int result = userMapper.updateById(currentUser);
//
//            return true;
//        } catch (Exception e) {
//            throw new RuntimeException("上传头像失败: " + e.getMessage());
//        }
//    }
    @Override
    public void delete(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("用户ID不能为空或无效");
        }

        try {
            int result = userMapper.deleteById(id);
            if (result <= 0) {
                throw new RuntimeException("删除用户失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("删除用户失败: " + e.getMessage());
        }
    }
}